import { fileURLToPath } from "url"; // 从 url 模块导入 fileURLToPath
import { dirname, join, resolve } from "path"; // 从 path 模块导入 dirname 和 join
import { createWriteStream, existsSync, mkdirSync } from "fs";

// 获取当前模块的路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const __rootname = resolve(__dirname, "../..");

// 日志文件路径
const logFilePath = join(__rootname, "error.log");

// 确保日志文件存在

if (!existsSync(logFilePath)) {
  // 如果日志文件不存在，创建它
  const logDir = dirname(logFilePath);

  if (!existsSync(logDir)) {
    mkdirSync(logDir, { recursive: true }); // 确保日志目录存在
  }
  createWriteStream(logFilePath); // 创建日志文件
}

// 写入日志的函数
export function logError(message) {
  const timestamp = new Date().toLocaleString("zh-CN");
  const logMessage = `${timestamp} - ${message}\n`;

  // 将错误信息追加到日志文件
  const logStream = createWriteStream(logFilePath, { flags: "a" });
  logStream.write(logMessage);
  logStream.close();
}
